package com.qiange.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qiange.common.Result;
import com.qiange.pojo.Category;
import com.qiange.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/category")
public class CategoryController {

    @Autowired
    private CategoryService categoryService;

    @GetMapping("/page")
    public Result<Page> getList(int page,int pageSize){
        LambdaQueryWrapper<Category> lqw = new LambdaQueryWrapper();
        Page<Category> byPage = new Page<>(page,pageSize);
        lqw.orderByAsc(Category::getSort);
        categoryService.page(byPage,lqw);
        return Result.success(byPage);
    }

    @PostMapping
//    @CacheEvict(value = "category:list",allEntries = true)
    public Result<String> addCategory(@RequestBody Category category){
        categoryService.save(category);
        return Result.success("添加成功");
    }

    @DeleteMapping
//    @CacheEvict(value = "category:list",allEntries = true)
    public Result<String> deleteById(Long id){
        categoryService.removeById(id);

        return Result.success("删除成功");
    }

//    @CacheEvict(value = "category:list",allEntries = true)
    @PutMapping
    public Result<String> update(@RequestBody Category category){
        LambdaQueryWrapper<Category> lqw = new LambdaQueryWrapper();
        lqw.eq(Category::getId,category.getId());

        categoryService.update(category,lqw);

        return Result.success("修改分类信息成功");
    }

    /**
     * 查询菜品分类信息，参数用实体类可以提高方法的可用范围
     * @param category
     * @return
     */
//    @Cacheable(value = "category:list",unless = "#result.data == null")
    @GetMapping("/list")
    public Result<List<Category>> getCategoryName(/*Integer type*/ Category category){

        LambdaQueryWrapper<Category> lqw = new LambdaQueryWrapper();
        lqw.eq(category.getType()!=null,Category::getType,category.getType());
        lqw.orderByAsc(Category::getSort);
        List<Category> list = categoryService.list(lqw);

        return Result.success(list);
    }
}
